// pages/album/bank.js
import request from '../../utils/request'
import calc from '../../utils/calc'
import WxNotificationCenter from '../../utils/WxNotificationCenter'

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    album: {},
    rankData: {},
    rewardData: {
      rewardAmount: 0,
      showCenterDialog: false,
      isEditing: false
    },
    account: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id: options.id,
      account: app.globalData.account
    })
    // 获取相册基本信息
    this.fetchAlbum()

    // 初始化列表数据
    this.initData()

    let that = this
    // 注册提现更行
    WxNotificationCenter.addNotification("withdraw", that.withdrawUpdate, that)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let album = this.data.album
    let title = '叔叔阿姨们给' + album.baby_name + '宝宝打赏了' + album.balance + '元，您也来参与吧'
    return {
      title: title,
      path: '/pages/album/index?id=' + album.id + '&share=true',
      imageUrl: album.icon
    }
  },

  /*
   * 提现成功后修改余额
   */
  withdrawUpdate: function (obj) {
    let album = this.data.album
    album.balance -= obj.amount
    this.setData({
      album: album
    })
  },

  /*
   * 获取相册信息
   */
  fetchAlbum() {
    let that = this
    let url = app.globalData.apiHost + '/albums/' + this.data.id
    wx.showLoading({
      title: '正在加载...',
    })
    request(url, 'GET', app.globalData.loginToken, {}, function (err, data) {
      console.log(data)
      wx.hideLoading()
      if (!err) {
        that.setData({
          album: data
        })
      }
    })
  },

  /*
   * 初始化打赏列表数据
   */
  initData(callback) {
    let that = this
    let url = app.globalData.apiHost + '/albums/' + this.data.id + '/reward_rank_list/'
    request(url, 'GET', app.globalData.loginToken, {}, function (err, data) {
      console.log(data)
      if (!err) {
        that.fixTotal(data)
        that.setData({ rankData: data })
      }
      if (callback) {
        return callback()
      }
    })
  },


  /*
   * 加载更多数据
   */
  loadMore() {
    let that = this
    let rankData = this.data.rankData
    if (rankData.next) {
      request(rankData.next, 'GET', app.globalData.loginToken, {}, function (err, data) {
        if (!err) {
          that.fixTotal(data)
          rankData.next = data.next
          rankData.previous = data.previous
          rankData.results = rankData.results.concat(data.results)
          that.setData({ rankData: rankData })
        }
      })
    }
  },

  /*
   * 修复返回的total数据
   */
  fixTotal(data) {
    for (let i = 0; i < data.results.length; i++) {
      let item = data.results[i]
      item.total = item.total.toFixed(1)
    }
  },

  /*
   * 打赏列表
   */
  viewRewardLog: function () {
    wx.navigateTo({
      url: 'rewardLog?id=' + this.data.id,
    })
  },
  
  /*
   * 去提现
   */
  goToWithdraw: function () {
    let balance = this.data.album.balance
    if (balance < 10) {
      return wx.showModal({
        title: '提示',
        showCancel: false,
        content: '小金库余额不少于10元才能提现！',
      })
    }
    wx.navigateTo({
      url: '../user/withdraw?id=' + this.data.id + '&balance=' + balance,
    })
  },

  /*
   * 非群主提示
   */
  withdrawTip: function () {
    wx.showModal({
      title: '提示',
      content: '只有相册的群主才能提现哦！',
      showCancel: false
    })
  },

  /******************* 打赏相关 **********************/
  /*
   * 打赏照片的对话框
   */
  rewardDialog: function (e) {
    let album = this.data.album
    let rewardAmount = calc.getRandomNum(0.1, 20)
    this.setData({
      rewardData: {
        showCenterDialog: true,
        rewardAmount: rewardAmount,
        isEditing: false,
        rewardTitle: '打赏' + album.title + '，金额随机'
      }
    })
  },

  /*
   * 取消打赏
   */
  closeReward: function (e) {
    this.setData({
      rewardData: {
        showCenterDialog: false,
        rewardAmount: 0,
        isEditing: false,
        rewardTitle: ''
      }
    })
  },

  /*
   * 刷新打赏金额
   */
  refreshReward: function (e) {
    let rewardData = this.data.rewardData
    let rewardAmount = calc.getRandomNum(0.1, 20)
    rewardData.rewardAmount = rewardAmount
    this.setData({
      rewardData: rewardData
    })
  },

  /*
   * 确认打赏
   */
  confirmReward: function (e) {
    let rewardData = this.data.rewardData
    let album = this.data.album
    let rewardAmount = rewardData.rewardAmount
    if (isNaN(rewardAmount)) {
      return wx.showToast({
        title: '请输入数字',
        image: '/images/icon/icon_attention.png'
      })
    }
    if (rewardAmount > 200) {
      return wx.showToast({
        title: '打赏金额不能超过200',
        image: '/images/icon/icon_attention.png'
      })
    }
    wx.showLoading({
      title: '请求中...',
      mask: true
    })
    let that = this
    let signData = {
      album: this.data.album.id,
      fee: rewardAmount * 100
    }
    let signUrl = app.globalData.apiHost + '/pay/get_wechat_prepay_id/'
    // 需要请求后台获取签名
    request(signUrl, 'post', app.globalData.loginToken, signData, function (err, data) {
      wx.hideLoading()
      if (!err) {
        let timeStamp = data.timeStamp.toString()
        wx.requestPayment({
          'timeStamp': timeStamp,
          'nonceStr': data.nonceStr,
          'package': data.package,
          'signType': data.signType,
          'paySign': data.paySign,
          success: function (res) {
            // 支付成功
            rewardData = {
              showCenterDialog: false,
              rewardAmount: 0,
              isEditing: false,
            }
            album.balance += rewardAmount
            that.setData({ rewardData: rewardData, album: album })
            wx.showToast({
              title: '打赏成功',
            })
            that.initData()
          },
          fail: function (res) {
            console.log(res)
          }
        })
      }
    })
  },

  /*
   * 编辑打赏金额
   */
  editAmount: function (e) {
    let rewardData = this.data.rewardData
    rewardData.isEditing = true
    this.setData({ rewardData: rewardData })
  },

  rewardAmountChange: function (e) {
    let rewardData = this.data.rewardData
    console.log(e.detail)
    rewardData.rewardAmount = parseFloat(e.detail.value)
    this.setData({ rewardData: rewardData })
  },

  endEditAmount: function (e) {
    let rewardData = this.data.rewardData
    rewardData.isEditing = false
    this.setData({ rewardData: rewardData })
  },
})